﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Jw.Models;
using Jw.Web.Areas.Qms.Common;
using System.Web.Http;
using Jw.Core;
using Jw.Web.App_Start;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace Jw.Web.Areas.Qms.Controllers
{
    public class LdphbzController : BaseController
    {
        //
        // GET: /Qms/Ldphbz/

        public ActionResult Index()
        {
            var codeService = new sys_codeService();
            var model = new
            {
                idField = "Ldphbz_BillNo", //主键
                urls = QmsHelper.GetIndexUrls("Ldphbz"),
                resx = QmsHelper.GetIndexResx("铝锭牌号标准"),
                dataSource = new
                {
                    yearItems = codeService.GetYearItems(),
                    monthItems = codeService.GetMonthItems()
                },
                form = new
                {
                    Ldphbz_Bmbh = "",
                    CreateDate = ""
                }

            };
            return View(model);
        }

        [MvcMenuFilter(false)]
        public ActionResult Edit(string id = "")
        {
            var data = new LdphbzApiController().GetEditMaster(id);
            var codeService = new sys_codeService();

            var model = new
            {
                form = data.form,
                scrollKeys = data.scrollKeys,
                urls = QmsHelper.GetEditUrls("Ldphbz"),
                resx = QmsHelper.GetEditResx("铝锭牌号标准"),
                dataSource = new
                {
                    //measureUnit = codeService.GetMeasureUnitListByType(),
                    //materialUse = codeService.GetValueTextListByType("MaterialUse"),
                    //billingUnit = codeService.GetValueTextListByType("BillingUnit")
                },
                defaultForm = new q_Ldphbz().Extend(new
                {
                    Ldphbz_BillNo = id,
                    Ldphbz_BillDate = DateTime.Now,
                    Ldphbz_Jyff = "光谱法", //检验方法
                    Ldphbz_Pdyj = "重熔用铝锭内控标准"
                }),
                defaultRow = new
                {
                    LdphbzDetail_Si = 0,
                    LdphbzDetail_Fe = 0,
                    LdphbzDetail_Cu = 0,
                    LdphbzDetail_Ca = 0,
                    LdphbzDetail_Mg = 0,
                    LdphbzDetail_Zn = 0,
                    LdphbzDetail_V = 0,
                    LdphbzDetail_Al = 0,
                    LdphbzDetail_Zzzh = 0
                },
                setting = new
                {
                    postFormKeys = new string[] { "Ldphbz_BillNo" },
                    //更新的明细字段
                    postListFields = new string[] { "LdphbzDetail_BillNo", "LdphbzDetail_RowId", "LdphbzDetail_Sybh", "LdphbzDetail_Si", "LdphbzDetail_Fe", "LdphbzDetail_Cu", "LdphbzDetail_Ca",
                                                    "LdphbzDetail_Mg","LdphbzDetail_Zn","LdphbzDetail_V","LdphbzDetail_Al","LdphbzDetail_Zzzh","LdphbzDetail_Ph","LdphbzDetail_Remark"}
                }
            };

            return View(model);
        }

    }

    //
    public class LdphbzApiController : ApiController
    {
        public string GetNewBillNo()
        {
            return new q_LdphbzService().GetNewKey("Ldphbz_BillNo", "dateplus");
        }
        public string GetNewRowId(int id, string BillNo)
        {
            return new q_LdphbzDetailService().GetNewKey("LdphbzDetail_RowId", "maxplus", id, ParamQuery.Instance().AndWhere("LdphbzDetail_BillNo", BillNo));
        }

        public dynamic Get(RequestWrapper query)
        {
            query.LoadSettingXmlString(@"
            <settings defaultOrderBy='Ldphbz_BillNo DESC'>
            <select>*</select>
                <from>q_Ldphbz</from>
                    <where defaultForAll='true' defaultCp='equal' defaultIgnoreEmpty='true' >
                        <field name='Ldphbz_Bmbh'     cp='like'></field>
                        <field name='Ldphbz_BillDate' cp='daterange'></field>
                    </where>
            </settings>");
            var service = new q_LdphbzService();
            var pQuery = query.ToParamQuery();
            var result = service.GetDynamicListWithPaging(pQuery);

            //var ff = new List<dynamic>();
            //ff.Add(new { Scsj_Rq = "本页小计", Scsj_Cy_Sddy = 100 });
            //ff.Add(new { Scsj_Ch = "合计", Scsj_Cy_Pjdy = 10 });
            //result.footer = ff;// JsonConvert.SerializeObject(ff);

            return result;
        }
        public dynamic GetEditMaster(string id)
        {
            q_Ldphbz obj = new q_LdphbzService().GetModel(ParamQuery.Instance().AndWhere("Ldphbz_BillNo", id));
            return new
            {
                form = obj,
                scrollKeys = new q_LdphbzService().ScrollKeys("Ldphbz_BillNo", id.ToString())
            };
        }

        // 地址：GET api/qms/Ldphbz/getdetail
        public dynamic GetDetail(string id)
        {
            var query = RequestWrapper
               .InstanceFromRequest()
               .SetRequestData("LdphbzDetail_BillNo", id)
               .LoadSettingXmlString(@"
<settings defaultOrderBy='LdphbzDetail_RowId'>
    <select>
        A.*
    </select>
    <from>
        q_LdphbzDetail A
    </from>
    <where>
        <field name='LdphbzDetail_BillNo' cp='equal'></field>
    </where>
</settings>");

            var pQuery = query.ToParamQuery();
            var result = new q_LdphbzDetailService().GetDynamicListWithPaging(pQuery);
            return result;

        }

        public void Edit(dynamic data)
        {
            var formWrapper = RequestWrapper.Instance().LoadSettingXmlString(@"
            <settings>
                <table>{0}</table>
                <where><field name='Ldphbz_BillNo' cp='equal'></field></where>
            </settings>", typeof(q_Ldphbz).Name);

            var listWrapper = RequestWrapper.Instance().LoadSettingXmlString(@"
            <settings>
                <table>{0}</table>
                <where>
                    <field name='LdphbzDetail_BillNo' cp='equal'></field>
                    <field name='LdphbzDetail_RowId'  cp='equal'></field>
                </where>
            </settings>", typeof(q_LdphbzDetail).Name);

            var result = new q_LdphbzService().Edit(formWrapper, listWrapper, data);
        }

        /// <summary>
        /// 删除主表（删除主表前是删除明细)
        /// </summary>
        /// <param name="id"></param>
        public void Delete(string id)
        {
            var result = new q_LdphbzService().Delete(ParamDelete.Instance().AndWhere("Ldphbz_BillNo", id));
            QmsHelper.ThrowHttpExceptionWhen(result <= 0, "单据删除失败[Ldphbz_BillNo={0}]，请重试或联系管理员！", id);
        }

        //审核
        [System.Web.Http.HttpPost]
        public void Audit(string id, JObject data)
        {
            var status = data["status"].ToString();
            var comment = data["comment"].ToString();
            var result = new QmsService().Audit(typeof(q_Ldphbz).Name, "Ldphbz_BillNo", id, status, comment);
            QmsHelper.ThrowHttpExceptionWhen(result < 0, "单据审核失败[Ldphbz_BillNo={0}]，请重试或联系管理员！", id);
        }
    }

}
